package com.sunny.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.glassfish.tyrus.server.Server;

@ServerEndpoint("/websockt/{token}")
public class WsServer {
	private final static String token = "token";
	private static ConcurrentHashMap<String, Session> webSocktClients = new ConcurrentHashMap<>();
	
	@OnOpen
	public void onOpen(Session session, @PathParam(token) String userid) {
		sendMessage(userid + "上线了...");
		webSocktClients.put(userid, session);
	}
	
	@OnClose
	public void onClose(@PathParam(token) String userid) {
		webSocktClients.remove(userid);
		sendMessage(userid + "下线了...");
	}
	
	@OnMessage
	public void onMessage(String message, @PathParam(token) String userid) {
		String[] user_msg = message.split(":");
		if (user_msg.length > 1) {
			System.out.println("服务端转发【" + userid + "】的消息给：【" + user_msg[0] + "】");
			sendMessageToUsers(user_msg[1], user_msg[0].split(","));
		} else {
			System.out.println("服务端转发【" + userid + "】的群消息.");
			sendMessage(message);
		}
	}
	
	@OnError
	public void onError(Throwable throwable) {
		throwable.printStackTrace();
	}
	
	/**
	 * 发送系统消息
	 * @param msg
	 * @return
	 */
	public static boolean sendMessage(String msg) {
		boolean flag = false;
		try {
			for (Session session : webSocktClients.values()) {
				session.getBasicRemote().sendText(msg);
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 发送个人消息或群组消息
	 * @param msg
	 * @param userids
	 * @return
	 */
	public static boolean sendMessageToUsers(String msg, String... userids) {
		boolean flag = false;
		try {
			if (userids != null && userids.length > 0) {
				for (String userid : userids) {
					webSocktClients.get(userid).getBasicRemote().sendText(msg);
				}
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	
	public static void main(String[] args) {
		Server server = new Server("localhost", 8080, "", null, WsServer.class);
		try {
			server.start();
			System.in.read();
		} catch (DeploymentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			server.stop();
		}
	}
}
